#include <pthread.h>
#include <stdio.h>

struct proc_attr {
	pthread_t tid1;
	pthread_t tid2;
	pthread_mutex_t sync_lock;
	pthread_cond_t sync_cond;
};

struct proc_attr env;

static int create_detached_thread(void *(*fn)(void *arg), void *arg);

void *loop1(void *arg)
{

	printf("[1]run loop1 ...\n");
	while(1) {
		pthread_mutex_lock(&env.sync_lock);
		printf("[1]waiting signal to fetch...\n");
		pthread_cond_wait(&env.sync_cond, &env.sync_lock);
		printf("[1]get signal\n");
		pthread_mutex_unlock(&env.sync_lock);
	}
}

void *loop2(void *arg)
{

	printf("[2]run loop2 ...\n");
	while(1) {
		printf("[2]sleep few seconds to put new data .... \n");
		sleep(1);
		pthread_mutex_lock(&env.sync_lock);
		pthread_cond_signal(&env.sync_cond);
		printf("[2]send signal\n");
		pthread_mutex_unlock(&env.sync_lock);
	}
}

int main()
{

	pthread_mutex_init(&env.sync_lock, NULL);
	pthread_cond_init(&env.sync_cond, NULL);

	create_detached_thread(loop1, 0);
	create_detached_thread(loop2, 0);

	while(1)
		sleep(10);
}

static int create_detached_thread(void *(*fn)(void *arg), void *arg)
{
	int ret;
	pthread_t tid;
	pthread_attr_t attr;

	ret = pthread_attr_init(&attr);
	if (ret != 0)
		return ret;

	ret = pthread_attr_setdetachstate(&attr, 
			PTHREAD_CREATE_DETACHED);
	if (ret == 0)
		ret = pthread_create(&tid, &attr, fn, arg);

	pthread_attr_destroy(&attr);
	return ret;
}
